package com.credit.core.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;

/**
 * 
 * 项目名称：core 类名称：DESXybUtil 类描述： des工具 创建人：huan 创建时间：2016年3月16日 下午2:04:24
 * 修改人：huan 修改时间：2016年3月16日 下午2:04:24 修改备注：
 * 
 * @version
 * 
 */
public class DESXybUtil {

    private static byte[] iv = { 2, 1, 3, 5, 4, 8, 7, 6 };

    public static String encryptDES(String encryptString, String secretKey) throws Exception {
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
        SecretKey key = factory.generateSecret(new DESKeySpec(secretKey.getBytes()));
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] binaryData = cipher.doFinal(encryptString.getBytes());
        byte[] bytes = Base64.encodeBase64(binaryData, true);
        return new String(bytes);
    }

    public static String decryptDES(String base64String, String secretKey) throws Exception {
        byte[] byteMi = Base64.decodeBase64(base64String);
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
        SecretKey key = factory.generateSecret(new DESKeySpec(secretKey.getBytes()));
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
        byte decryptedData[] = cipher.doFinal(byteMi);
        return new String(decryptedData);
    }

    /**
     * @see 三重des加密
     * 
     */
    public static String encryptThreeDES(String encryptString, String secretKey) throws Exception {
        String encryptDES1 = encryptDES(encryptString, secretKey);
        String encryptDES2 = encryptDES(encryptDES1, secretKey);
        String encryptDES3 = encryptDES(encryptDES2, secretKey);
        return encryptDES3;
    }

    /**
     * @see 三重des解密
     */
    public static String decryptThreeDES(String encryptDES, String secretKey) throws Exception {
        String result = decryptDES(encryptDES, secretKey);
        String result2 = decryptDES(result, secretKey);
        String result3 = decryptDES(result2, secretKey);
        return result3;
    }

    public static void main(String[] args) throws Exception {

        String encryptThreeDES = encryptThreeDES("3372495", "woaika_licai");
        System.out.println(encryptThreeDES);
        String decryptDES = decryptThreeDES("uvnIIXARUKmso56pO+l7Xv6hf+n5deFGgu5o4h2qUgbdrHNhyx+YtLdyhVumao/b\r\n",
                "woaika_licai");
        System.out.println(decryptDES);
    }
}
